package com.oa.oaspccommon.interceptor;

import com.google.gson.Gson;

import com.oa.oaspccommon.anonotation.JwtAuthen;
import com.oa.oaspccommon.util.JwtUtil;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Sdx
 * 2021-04-17
 */
public class AuthenInterceptor implements HandlerInterceptor {
    //进入处理器方法前激发
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag = false;
        if (handler instanceof HandlerMethod) {//是否处理器方法
            HandlerMethod method = (HandlerMethod) handler;
//            从处理器方法中获取权限注解
            JwtAuthen jwtAuthen = method.getMethodAnnotation(JwtAuthen.class);
            if (jwtAuthen != null) {//含权限注解，必须校验令牌合法
                String methodDesc = jwtAuthen.name();//获取方法的描述，后续可以记录日志
                String token = request.getHeader("authoritation");
                boolean check = JwtUtil.checkToken(token);
                if (check) {
                    flag = true;
                } else {//令牌无效，无权访问
                    response.setContentType("application/json;charset=UTF-8");
//                    返回json消息
                    PrintWriter out = response.getWriter();
                    Map json = new HashMap();
                    json.put("statusCode", -100);
                    json.put("msg", "this user auth id invalid");
                    String s = new Gson().toJson(json);
                    out.write(s);
                    flag = false;
                }
            }else {
                flag=true;
            }
        }else{
            flag=true;
        }
//            添加拦截器
        return flag;
    }

    //执行完处理器方法返回逻辑视图后被激发
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("posthandler......");
    }

    //获取试图后被激发
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterhandler......");
    }
}
